const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const rateLimit = require('express-rate-limit');
const router = express.Router();
const SMS = require('../models/SMS');
//配置信息
const mailConfig = {
    host: "smtp.yeah.net",
    port: 465,
    auth: {
        user: 'kvxin_l@yeah.net',
        pass: 'CHASQOQHTUJPRWPQ',
    },
    secure: true
}

//邮件传输器
const transporter = nodemailer.createTransport(mailConfig);
router.post('/sendVerification', (req, res) => {
    const email = req.body.params.email;
    console.log(email);
    const verificationCode = Math.floor(100000 + Math.random() * 900000);
    //查询数据库中是否有相同的邮箱，如果有相同的邮箱，就返回一个请求次数过多，如果没有，就代表他没有发送过邮件，给他发过去
    //发过去之后将数据存起来，当验证成功的时候就删除掉这个数据
    findUser(email).then((response => {
        send(email, verificationCode);
        res.status(200).json({ message: "邮件已发送成功,请注意查收邮箱~" })
    })).catch(err => {
        res.status(429).json({ message: "请求次数过多" })
    })
})


const send = (email, verificationCode) => {
    const mail = {
        // 发件人
        from: '<' + mailConfig.auth.user + '>',
        // 主题
        subject: '邮箱验证',
        // 收件人
        to: email,
        html: '<h1>尊敬的用户您好：</h1><br>' +
            '<h5> 您正在进行邮箱验证，本次验证码为：<span style="color:#ec0808;font-size: 20px;">' + verificationCode + '</span>，请在10分钟内进行使用。</h5>' +
            '<h5>如非本人操作，请忽略此邮件，由此给您带来的不便请谅解！</h5> <h5 style="text-align: right;"></h5>'
    }
    transporter.sendMail(mail, function (error, info) {
        if (error) {
            console.log("发送失败", error)
        } else {
            addSMS(email, verificationCode)
        }
    })
}
const findUser = async (email) => {
    try {
        const findCondition = { email: email };
        const emails = await SMS.find(findCondition);
        if (emails.length) {
            return Promise.reject();
        } else {
            return Promise.resolve();
        }
    } catch (error) {
        console.error('查找用户时出错:', error);
    }
}

const addSMS = async (email, code) => {
    try {
        const newSMS = new SMS({
            email: email,
            code: code,
        })
        await newSMS.save();
        return Promise.resolve();
    } catch (error) {
        console.log('插入错误~', error);
        return Promise.reject(error);
    }
}
module.exports = router;